<template>
  <el-dialog
    v-model="drawerVisible"
    :title="drawerProps.title"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleClose"
    width="800px"
    top="5vh"
    class="work-log-drawer"
  >
    <el-form
      ref="ruleFormRef"
      :model="drawerProps.row"
      :rules="rules"
      label-width="100px"
      label-suffix=" :"
      label-position="right"
      status-icon
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="工作日期" prop="workDate">
            <el-date-picker
              v-model="drawerProps.row!.workDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择工作日期"
              :disabled="drawerProps.isView"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="工作内容" prop="summary">
            <el-input
              v-model="drawerProps.row!.summary"
              :rows="6"
              type="textarea"
              placeholder="请输入工作总结"
              :disabled="drawerProps.isView"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="工作思考" prop="think">
            <el-input
              v-model="drawerProps.row!.think"
              :rows="6"
              type="textarea"
              placeholder="请输入工作思考"
              :disabled="drawerProps.isView"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="handleClose"> 取消 </el-button>
      <el-button v-if="!drawerProps.isView" type="primary" @click="handleSubmit" :loading="loading"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="workLogDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { WorkLog } from "@/api/types/base";
import { useUserStore } from "@/stores/modules/user";

const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const drawerVisible = ref(false);

const drawerProps = reactive({
  title: "",
  isView: false,
  tbName: "",
  row: {} as Partial<WorkLog>,
  api: undefined as any,
  getTableList: undefined as any
});

// 表单验证规则
const rules = reactive({
  workDate: [{ required: true, message: "请选择工作日期", trigger: "change" }],
  summary: [{ required: true, message: "请输入工作总结", trigger: "blur" }],
  think: [{ required: true, message: "请输入工作思考", trigger: "blur" }]
});

// 接收父组件参数
const acceptParams = (params: any) => {
  Object.assign(drawerProps, params);
  // 如果是新增，设置默认日期为今天
  if (params.title === "新增") {
    drawerProps.row.workDate = new Date().toISOString().slice(0, 10);
    drawerProps.row.think = "无";
  }
  drawerVisible.value = true;
};

// 关闭弹窗
const handleClose = () => {
  drawerVisible.value = false;
  ruleFormRef.value?.resetFields();
  drawerProps.row = {} as Partial<WorkLog>;
};

// 提交数据
const handleSubmit = () => {
  ruleFormRef.value?.validate(async valid => {
    if (!valid) return;
    loading.value = true;

    try {
      // 如果是编辑且没有_id，则从原始数据中获取
      if (drawerProps.title === "新增") {
        drawerProps.row.create_at = new Date();
        drawerProps.row.create_user = useUserStore().userInfo._id;
        drawerProps.row.userId = useUserStore().userInfo._id;
      }

      await drawerProps.api(drawerProps.tbName, drawerProps.row);
      ElMessage.success(`${drawerProps.title}工作日志成功！`);
      drawerProps.getTableList && drawerProps.getTableList();
      handleClose();
    } catch (error) {
      console.error(error);
      ElMessage.error(`${drawerProps.title}工作日志失败！`);
    } finally {
      loading.value = false;
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
.work-log-drawer {
  :deep(.el-textarea__inner) {
    font-family: inherit;
  }
}
</style>
